package com.le.buddha.websocket;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.le.buddha.mobile.ConnectRecord;
import com.le.buddha.mobile.User;
import com.le.buddha.mobile.VoiceModel;
import com.le.buddha.mobile.enums.ConnectRecordEnum;
import com.le.buddha.mobile.enums.SysConfigEnum;
import com.le.buddha.service.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 连接开启逻辑处理
 *
 * @author guole
 * @created 2025/6/11
 */
@Service
public class OpenHandle {
    @Resource
    private ISysConfigService sysConfigService;
    @Resource
    private IVoiceService voiceService;
    @Resource
    private IVoiceModeService voiceModeService;
    @Resource
    private IFileService fileService;

    @Resource
    private IUserService userService;
    @Resource
    private IConnectRecordService connectRecordService;

    @Value("${fileServer}")
    private String fileUrl;

    public void handle(String oid) {
        User user = userService.queryUserByToken(oid);
        Assert.notNull(user, "获取不到用户");
        if(connectRecordService.lambdaQuery().eq(ConnectRecord::getUserId,user.getId()).count()==0){
            String welcomeTxt = sysConfigService.queryValueByCode(SysConfigEnum.注册登录欢迎语.getCode());
            Long voiceId = Long.parseLong(sysConfigService.queryValueByCode(SysConfigEnum.声音模型ID.getCode()));
            VoiceModel voiceModel = voiceModeService.lambdaQuery().eq(VoiceModel::getId, voiceId).one();
            String modelName = voiceModel.getModelName();
            Integer speech = voiceModel.getSpeech();

            byte[] music = voiceService.textToSpeech(welcomeTxt, modelName, speech);
            String path = fileUrl + fileService.upload(music, "mp3", 2);
            //发送文本
            WebSocketSever.sendMessageByUser(oid, welcomeTxt, 1);
            //发送语音
            WebSocketSever.sendMessageByUser(oid, path, 2);

        }




        //插入开启连接记录数据
        Date now = new Date();
        user.setConnectStatus(1);
        user.setUpTime(now);
        userService.updateById(user);
        ConnectRecord connectRecord = new ConnectRecord();
        connectRecord.setCreateDate(now);
        connectRecord.setType(ConnectRecordEnum.上线.getCode());
        connectRecord.setUserId(user.getId());
        connectRecordService.save(connectRecord);

    }


}
